<?php

namespace app\api\controller\meet;

use addons\third\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use app\common\model\meet\Config;
use EasyWeChat\Factory;

class User extends Api
{
    protected $noNeedLogin = ['login'];

    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    public function login()
    {
        $code = $this->request->get('code', '');

        if (empty($code)) {
            $this->error(__('Parameter %s can not be empty', 'code'));
        }

        $config = [
            'app_id' => Config::getConfigByName('mini_appid')['value'],
            'secret' => Config::getConfigByName('mini_appsecret')['value'],
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);

        $result = $app->auth->session($code);

        if (isset($result['openid'])) {
            $token = $this->request->post('token');
            //如果有传Token
            if ($token) {
                $this->auth->init($$token);
                //检测是否登录
                if ($this->auth->isLogin()) {
                    $third = Third::where(['openid' => $result['openid'], 'platform' => 'wxapp'])->find();
                    if ($third && $third['user_id'] == $this->auth->id) {
                        //把最新的 session_key 保存到 第三方表的 access_token 里
                        $third['access_token'] = $result['session_key'];
                        $third->save();
                        $this->success(__('Login successful'), $this->Format_avatarUrl($this->auth->getUserinfo()));
                    }
                }
            }

            $platform = 'wxapp';

            $data = [
                'openid' => $result['openid'],
                'unionid' => $result['unionid'],
                'userinfo' => [
                    'nickname' => '',
                ],
                'access_token' => $result['session_key'],
                'refresh_token' => '',
                'expires_in' => isset($result['expires_in']) ? $result['expires_in'] : 0,
            ];


            $extend = ['mobile' => '', 'gender' => Null, 'nickname' => '', 'avatar' => '/assets/img/avatar.png'];

            $ret = Service::connect($platform, $data, $extend);
            if ($ret) {
                $this->success(__('Login successful'), $this->Format_avatarUrl($this->auth->getUserinfo()));
            } else {
                $this->error(__('Login failed'));
            }
        } else {
            $this->error(__('Error code:%s，%s', [$result['errcode'], $result['errmsg']]));
        }
    }

    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname/s', '');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');

        if ($nickname) {
            $user->nickname = $nickname;
        }

        if ($avatar) {
            $user->avatar = $avatar;
        }

        $user->save();

        $user = $this->auth->getUserinfo();
        $user['avatar'] = cdnurl($user['avatar'], true);
        $this->success('', ['userInfo' => $user]);
    }

    public function decryptPhoneNumber()
    {
        $code = $this->request->post('code', '');
        if (empty($code)) {
            $this->error(__('Invalid parameters'));
        }

        $config = [
            'app_id' => Config::getConfigByName('mini_appid')['value'],
            'secret' => Config::getConfigByName('mini_appsecret')['value'],
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);

        $result = $app->getPhoneNumber($code);

        if ($result['errcode'] == 0) {
            $user = $this->auth->getUser();

            //新人注册
            (new \app\common\model\User())->grantCoupon($user->id, 'register');

            $user->mobile = $result['phone_info']['phoneNumber'];

            $user->save();

            $user = $this->auth->getUserinfo();
            $user['avatar'] = cdnurl($user['avatar'], true);

            $this->success('', ['userInfo' => $user]);
        } else {
            $this->error($result['errmsg']);
        }
    }

    /**
     * 分享赠送优惠券
     */
    public function share()
    {
        (new \app\common\model\User())->grantCoupon($this->auth->id, 'share');

        $this->success();
    }

    private function Format_avatarUrl($userInfo)
    {
        $avatar = $userInfo['avatar'];
        if ($this->startsWith($avatar, "/uploads/")) {
            $userInfo['avatar'] = cdnurl($avatar, true);
        }

        $userInfo['avatar'] = $userInfo['avatar'] ? cdnurl($userInfo['avatar'], true) : cdnurl('/assets/img/avatar.png', true);

        return ['userInfo' => $userInfo];
    }

    private function startsWith($str, $prefix)
    {
        for ($i = 0; $i < strlen($prefix); ++$i) {
            if ($prefix[$i] !== $str[$i]) {
                return false;
            }
        }
        return true;
    }
}
